package dfsketches.gr3d;

public class Geodata {
	
	private Matrix3D trans;
	private Matrix3D revtrans;
	private int[][] map;
	private float size;
	
	public Geodata(int[][] map, Matrix3D trans) {
		this.map = map;
		this.trans = trans;
		revtrans = trans.reverse();
		size = map.length;
	}
	
	/**
	 * Finds projection of v on the surface.
	 * @param v
	 */
	public Vector3D drop(Vector3D v) {
		v = new Vector3D(v);
		v.apply(revtrans);
		if (v.x < 1f && v.x >= 0f && v.z < 1f && v.z >= 0f) {
			int x = (int)(v.x * size);
			int z = (int)(v.z * size);
			if (x == size-1 || z == size-1) {
				v = new Vector3D(v.x, map[x][z], v.z);
			} else {

				float dx = v.x * size - x;
				float dz = v.z * size - z;
				float _dx = 1 - dx;
				float _dz = 1 - dz;
				float y = _dx*_dz*map[x][z] + dx*_dz*map[x+1][z] + _dx*dz*map[x][z+1] + dx*dz*map[x+1][z+1];
				v = new Vector3D(v.x, y, v.z);
			}
		}
		v.apply(trans);
		return v;
	}
	
}
